package com.gimi.cloud.jimi.queue.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.DateUtil;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.commonService.InterfacePlatform.InterfacePlatformRequestService;
import com.gimi.cloud.jimi.dao.dao.User.UserDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoLogDao;
import com.gimi.cloud.jimi.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.jimi.dao.redis.IRedisService;
import com.gimi.cloud.jimi.dto.app.moreInfo.GongjijingDTO;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoEntity;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoLogEntity;
import com.gimi.cloud.jimi.entity.user.User;
import com.gimi.cloud.jimi.queue.service.FengchaoGongjijingService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


/**
 * 蜂巢公积金服务
 *
 * @author lilinfeng
 */
@Service
public class FengchaoGongjijingServiceImpl implements FengchaoGongjijingService {

    private static final Logger log = LoggerFactory.getLogger(FengchaoGongjijingServiceImpl.class);
    private IRedisService iRedisService;
    private InterfacePlatformRequestService ipRequestService;
    private MoreInfoDao moreInfoDao;
    private MoreInfoLogDao moreInfoLogDao;
    private UserDao userDao;
    private SysConfigDao sysConfigDao;
    //最大容错次数暂时定为3次
    private final Integer MAXTIMES = 3;

    private final static String INTERFACE_PLATFORM_UNIVERSAL_GETPROVIDENTFUNDINFO = "interface_platform_universal_getProvidentFundInfo";

    @Autowired
    public FengchaoGongjijingServiceImpl(IRedisService iRedisService, InterfacePlatformRequestService ipRequestService, MoreInfoDao moreInfoDao, UserDao userDao
            , SysConfigDao sysConfigDao, MoreInfoLogDao moreInfoLogDao) {
        this.iRedisService = iRedisService;
        this.ipRequestService = ipRequestService;
        this.moreInfoDao = moreInfoDao;
        this.userDao = userDao;
        this.sysConfigDao = sysConfigDao;
        this.moreInfoLogDao = moreInfoLogDao;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void getReport(GongjijingDTO gongjijingDTO) throws Exception {
        log.info("开始获取公积金报告");

        log.info("验证参数");
        if (gongjijingDTO == null || StringUtil.isBlank(gongjijingDTO.getUserId()) || StringUtil.isBlank(gongjijingDTO.getSurnameSid())
                || StringUtil.isBlank(gongjijingDTO.getLocationCid())) {
            throw new MsgException(ResponseCodeEnum.GOJIJING_IS_NOT_FOUND);
        }

        User user = userDao.getUserByUserId(gongjijingDTO.getUserId());
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        //查询该用户之前是否有获取过社保信息，需要获取状态为获取中
        MoreInfoEntity moreInfoEntity = moreInfoDao.getMoreInfoByUserIdAndTypeAndData(gongjijingDTO.getUserId(),6,1);
        if (moreInfoEntity == null || moreInfoEntity.getGetdataErrorTimes() >= MAXTIMES) {
            throw new MsgException(ResponseCodeEnum.GONGJIJING_DATA_ERROR_TIMES_IS_OUT_OF_TIMES);
        }

        log.info("读取数据库配置表");
        String fengchao_gongjijing = sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_GETPROVIDENTFUNDINFO);
        JSONObject fgJson = JSON.parseObject(fengchao_gongjijing);
        JSONObject getgjjdetail = fgJson.getJSONObject("fengchao_gongjijin_getgjjdetail");

        log.info("组装请求参数");
        JSONObject body = getgjjdetail.getJSONObject("body");
        body.put("surname_sid", gongjijingDTO.getSurnameSid());
        body.put("location_cid", gongjijingDTO.getLocationCid());
        getgjjdetail.put("body", body);

        log.info("发起请求获取报告");
        String sendApiPost = ipRequestService.sendApiPost(getgjjdetail.toJSONString());

        //新建日志记录
        MoreInfoLogEntity moreInfoLogEntity =new MoreInfoLogEntity();
        moreInfoLogEntity.setUserId(user.getUserId());
        moreInfoLogEntity.setType("6");
        moreInfoLogEntity.setAddTime(DateUtil.getNow());
        moreInfoLogEntity.setResponseData(sendApiPost);
        moreInfoLogEntity.setRequestData(getgjjdetail.toJSONString());

        JSONObject reportJson = JSON.parseObject(sendApiPost);
        JSONObject reportbody = reportJson.getJSONObject("body");
        JSONObject data = reportbody.getJSONObject("data");
        String type = reportbody.getString("type");

        //只有type为1的时候为成功，其他情况都是失败
        if (reportbody != null && "1".equals(type)) {
            //存入数据
            moreInfoEntity.setReportData(data.getString("ossUrl"));
            moreInfoEntity.setGetdataErrorTimes(0);
            moreInfoEntity.setGetdataTime(DateUtil.getNow());
            //TODO 有效时长，等风控规则
            moreInfoEntity.setReportEffectionBegin(DateUtil.getNow());
            moreInfoEntity.setReportEffectionEnd(DateUtil.getLateYear(1));
            moreInfoEntity.setGetdata("2");
            moreInfoEntity.setUpdateUid(user.getUserId());
            moreInfoEntity.setUpdateUname(user.getAddUname());
            moreInfoEntity.setUpdateTime(DateUtil.getNow());
            moreInfoEntity.setBaRemark("");
            //抓取状态（1成功，2失败）
            moreInfoLogEntity.setStatus(1);

        } else {
            moreInfoEntity.setGetdataErrorTimes(moreInfoEntity.getGetdataErrorTimes() + 1);
            moreInfoEntity.setGetdata("3");
            moreInfoEntity.setUpdateUid(user.getUserId());
            moreInfoEntity.setUpdateUname(user.getAddUname());
            moreInfoEntity.setUpdateTime(DateUtil.getNow());
            String obj = "";
            if (reportbody != null) {
                String errors = data.getString("errors");
                if (StringUtils.isNotBlank(errors)) obj = errors;
            } else {
                obj = sendApiPost;
            }
            if (obj.length() > 150) {
                obj = obj.substring(0, 150);
            }
            moreInfoEntity.setBaRemark(obj);

            //抓取状态（1成功，2失败）
            moreInfoLogEntity.setStatus(2);
        }

        moreInfoLogDao.insertSelective(moreInfoLogEntity);
        moreInfoDao.updateByPrimaryKey(moreInfoEntity);
        log.info("获取公积金报告结束");
    }

}